package com.xiaoquan.gulimall.product.service.impl;

import com.xiaoquan.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoquan.common.utils.PageUtils;
import com.xiaoquan.common.utils.Query;

import com.xiaoquan.gulimall.product.dao.BrandDao;
import com.xiaoquan.gulimall.product.entity.BrandEntity;
import com.xiaoquan.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        // 1、获取key
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            // TODO 品牌搜索功能
            // 传进来的参数key  有可能时id  也有可能时名字
            queryWrapper.eq("brand_id",key).or().like("name",key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    // TODO 保证所有关联的数据一致
    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        // 保证冗余字段的数据一致
        // 先更新自己表中的id
         this.updateById(brand);
         if (!StringUtils.isEmpty(brand.getName())){
             // 如果品牌名不为空 其他表里面也会存品牌名
             // 同步更新其他表中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());

            // TODO 更新其他关联
         }
    }

    @Override
    public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        wrapper.in("brand_id",brandIds);
       return this.list(wrapper);
    }

}